package jq.action;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import jq.core.text.TextUtil;
import jq.core.text.WebPageUtil;
import jq.entity.Currency;

public class UpdateCurrencyAction {
	private Logger log = LoggerFactory.getLogger(UpdateCurrencyAction.class);
	private boolean IS_DEBUG=true;
	public List<Currency> updateCurrency() throws IOException {
		List<Currency> result = new ArrayList<Currency>();
		Map<String, String> curList = new HashMap<String, String>();
		String homePage = new WebPageUtil().fetchPageContent("http://www.iccfx.com");
		TextUtil util = new TextUtil(homePage);
		while (util.selectText("OPTION>", "<")) {
			String value = util.extractText();
			String[] parts = parseNameAndCode(value);
			curList.put(parts[1], parts[0]);
		}
		Set<Entry<String, String>> entries = curList.entrySet();
		Iterator<Entry<String, String>> iter = entries.iterator();
		String from = URLEncoder.encode("US Dollar (USD)", "UTF-8");
		int times=0;
		while (iter.hasNext()) {
			if(times>3 && IS_DEBUG){
				break;
			}
			Entry<String, String> each = iter.next();
			String name = each.getValue();
			String code = each.getKey();
			if (log.isDebugEnabled()) log.debug(name + "\t" + code);
			// build the url address
			if (name.equals("US Dollar")) {
				continue;
			}

			String to = URLEncoder.encode(name + " (" + code + ")", "UTF-8");
			String url = "http://www.iccfx.com/convert.php";
			String data = "showall=&to=" + to + "&amount=1&from=" + from;
			if (log.isDebugEnabled()) log.debug(url+"?"+data);
			String content = new WebPageUtil().fetchPageContent(url, "POST", data);
			if(content==null){
				if(log.isErrorEnabled()) log.error("update currency for "+name+"\t"+code+" failed.");
				continue;
			}
			TextUtil u1 = new TextUtil(content);
			if (u1.selectText("<B>1</B> US Dollar (USD) = <B>", "</B>")) {
				String value = u1.extractText().trim();
				Double d = 0d;
				try {
					d = Double.parseDouble(value);
				} catch (Exception e) {

				}
				Currency c = new Currency(name, code, d);
				if(log.isDebugEnabled()) log.debug("Add a currency:"+c.toString());
				result.add(c);
			}
			times++;
		}
		return result;
	}

	public String[] parseNameAndCode(String value) {
		int from = value.indexOf("(");
		int end = value.indexOf(")", from);
		String name = value.substring(0, from).trim();
		String code = value.substring(from + 1, end).trim();
		return new String[]{name, code};
	}

	public static void main(String args[]) throws IOException {
		UpdateCurrencyAction u=new UpdateCurrencyAction();
		u.updateCurrency();
	}
}
